/**
 * @api post model.
 *
 * User: yunshengzhu
 * Date: 2020/12/7
 * Time: 下午6:15
 */
package model

func CreateLogistics(obj LogisticsDb) error {
	tx := db.Begin()
	if obj.Main == 1 {
		err := tx.Exec(`update t_user_logistics set main=0 where user_id=?`, obj.UserId).Error
		if err != nil {
			tx.Rollback()
			return err
		}
	}
	err := tx.Create(&obj).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

func UpdateLogistics(obj LogisticsDb) error {
	tx := db.Begin()
	if obj.Main == 1 {
		err := tx.Exec(`update t_user_logistics set main=0 where user_id=?`, obj.UserId).Error
		if err != nil {
			tx.Rollback()
			return err
		}
	}

	err := tx.Select("postal_code,area_code,main,mobile,town_name,county_name,city_name,province_name,address,name").Where("logistics_id=?", obj.LogisticsId).Updates(&obj).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

func GetLogisticsList(userId int64) (list []LogisticsDb, err error) {
	list = make([]LogisticsDb, 0)
	return list, db.Where("user_id=?", userId).Find(&list).Error
}

func DelLogistics(logisticsId int64) error {
	return db.Exec("delete from t_user_logistics where logistics_id=?", logisticsId).Error
}

func GetLogisticsUserIdAndId(userId int64, logisticsId int64) (obj LogisticsDb, err error) {
	return obj, db.Where("user_id=? and logistics_id=?", userId, logisticsId).Take(&obj).Error
}

func GetLogisticsUserIdMain(userId int64) (obj LogisticsDb, err error) {
	return obj, db.Where("user_id=?", userId).Order("main desc").First(&obj).Error
}
